<template>
    <div class="post-list">
        <PostCreate @success="handlePostCreated" />
        <!-- 编辑帖子对话框 -->
        <PostEdit v-model:visible="editDialogVisible" :post="editingPost" @success="handleEditSuccess" />

        <div v-if="loading && posts.length === 0" class="loading-state">
            <el-icon class="is-loading">
                <Loading />
            </el-icon>
            <span>加载中...</span>
        </div>

        <template v-else>
            <!-- 搜索状态提示 -->
            <div v-if="isSearching" class="search-status">
                <div class="search-info">
                    <span>搜索"{{ props.searchKeyword }}" ({{ searchTypeText }})</span>
                    <el-button type="text" @click="clearSearch">清除搜索</el-button>
                </div>
                <div v-if="posts.length === 0" class="no-results">
                    <el-empty description="没有找到相关动态" />
                </div>
            </div>

            <PostItem v-for="post in posts" :key="post.post_id" :post="post" @update="handleUpdatePost"
                @delete="handleDeletePost" @refresh="handleRefresh" />

            <div v-if="posts.length === 0 && !isSearching" class="empty-state">
                <el-empty description="暂无动态" />
            </div>

            <div v-if="posts.length > 0 && !isSearching" class="no-more">
                已显示全部动态
            </div>
        </template>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { usePostsStore } from '@/stores/posts'
import PostCreate from './PostCreate.vue'
import PostItem from './PostItem.vue'
import PostEdit from './PostEdit.vue'
import { storeToRefs } from 'pinia'

const props = defineProps({
    searchKeyword: {
        type: String,
        default: ''
    },
    searchType: {
        type: String,
        default: 'post'
    }
})

const emit = defineEmits(['refresh'])

const postsStore = usePostsStore()
const { posts, loading } = storeToRefs(postsStore)

const editDialogVisible = ref(false)
const editingPost = ref(null)

// 计算属性
const isSearching = computed(() => {
    return !!props.searchKeyword
})

const searchTypeText = computed(() => {
    return props.searchType === 'post' ? '动态内容' : '用户昵称'
})

// 监听搜索条件变化
watch(() => [props.searchKeyword, props.searchType], () => {
    if (props.searchKeyword) {
        handleSearch()
    } else {
        // 清除搜索，恢复正常列表
        postsStore.resetPagination()
        postsStore.fetchPosts()
    }
}, { immediate: true })

const handleSearch = async () => {
    if (!props.searchKeyword) return

    try {
        postsStore.resetPagination()
        await postsStore.fetchPosts({
            search_keyword: props.searchKeyword,
            search_type: props.searchType,
            page: 1,
            pageSize: 1000 // 搜索时也加载全部
        })
    } catch (error) {
        console.error('搜索失败:', error)
        ElMessage.error('搜索失败')
    }
}
const clearSearch = () => {
    emit('refresh')
}

const handlePostCreated = () => {
    postsStore.resetPagination()
    postsStore.fetchPosts()
}

const handleUpdatePost = (post) => {
    editingPost.value = post
    editDialogVisible.value = true
}

const handleEditSuccess = () => {
    editDialogVisible.value = false
    editingPost.value = null
    // 刷新帖子列表
    if (isSearching.value) {
        handleSearch() // 如果是搜索状态，重新搜索
    } else {
        postsStore.fetchPosts()
    }
    ElMessage.success('更新成功')
}

const handleDeletePost = (postId) => {
    // 刷新帖子列表
    if (isSearching.value) {
        handleSearch() // 如果是搜索状态，重新搜索
    } else {
        postsStore.fetchPosts()
    }
    ElMessage.success('删除成功')
}

const handleRefresh = () => {
    // 刷新帖子列表以更新评论数等
    if (isSearching.value) {
        handleSearch()
    } else {
        postsStore.fetchPosts()
    }
}

onMounted(() => {
    if (posts.value.length === 0) {
        postsStore.fetchPosts({ pageSize: 1000 }) // 初始加载全部
    }
})
</script>

<style scoped>
.post-list {
    max-width: 1000px;
    margin: 0 auto;
}

.loading-state {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #999;
    gap: 8px;
}

.empty-state {
    padding: 40px 0;
}

.no-more {
    text-align: center;
    padding: 20px;
    color: #999;
    font-size: 14px;
}

/* 搜索状态样式 */
.search-status {
    margin-bottom: 16px;
}

.search-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    background: #f0f9ff;
    border: 1px solid #e6f7ff;
    border-radius: 6px;
    color: #1890ff;
    font-size: 14px;
}

.no-results {
    padding: 40px 0;
    text-align: center;
}
</style>